
package com.vanda.db.convert;
import java.util.HashMap;
import org.apache.commons.beanutils.PropertyUtils;

/**
 * 参数转换工厂类<br>
 * 例如:
 * 一般的Object类型,对应的xql是?,
 * 如果是Collection类型,对应的xql是?,?...
 *
 * @author 王瑛<br>
 * @version Version 1.00<br>
 */
public class ConvertFactory {
	/**
	 * 返回Convert不同的实例
	 * @param property 用{}括起来的值，形式如下：object.field
	 * @param params 见LogicTag.parse的描述
	 * @return
	 */
	public static Convert getInstance(String property, HashMap params)
		throws Exception {
		//取得property的前缀和后缀
		property = property.trim();
		int index = property.indexOf(".");
		if (index == -1) {
			throw new Exception("Property [" + property + "] error!");
		}
		String paramName = property.substring(0, index);
		property = property.substring(index + 1, property.length());
		//取得paramName对应的实例
		Object obj = params.get(paramName);
		if (obj == null) {
			throw new Exception("Param Name [" + paramName + "] not exist!");
		}
		Object objParam = PropertyUtils.getProperty(obj, property);
		Convert dialect = null;
		if (objParam == null) {
			dialect = new NullConvert();
		} else if (objParam instanceof java.util.Collection) {
			dialect = new CollectionConvert();
		} else {
			dialect = new ObjectConvert();
		}
		dialect.setParam(objParam);
		return dialect;
	}
}
